var AddWarehouseByReturnToProvider = function () {
  var template = /*html*/ `
    <div class="approvalReutrnMaterialToProvider" v-loading.fullscreen.lock="loading">
      <div>
        <search-btn-view immediate btn-text="查询条件" @before-open="resetSearch" @search="searchData">
          <template slot="append">
            <el-button size="medium" type="primary" @click="saveData(false)">确认入库</el-button>
            <el-button size="medium" type="primary" @click="saveData(true)" :disabled="!selfApprovalPermission">审核过账</el-button>
            <el-button v-if="checkData.length>0" size="medium" type="primary" @click="deleteData">批量删除</el-button>
          </template>
          <div slot="search-content">
            <sys-common-search request-url="materialSelectFilter/getMaterialSelectData" :request-data="{type:18}"
              :search="search" :search-field="searchField" label-width="100px" input-width="180px">
              <template slot="prepend">
                <el-form-item label="退货日期">
                  <el-date-picker v-model="search.startDate" style="width:229px;" value-format="timestamp" :editable="false"
                    :picker-options="startDateOption" placeholder="退货开始日期"></el-date-picker>
                  -
                  <el-date-picker v-model="search.endDate" style="width:229px;" value-format="timestamp" :editable="false"
                    :picker-options="endDateOption" placeholder="退货结束日期"></el-date-picker>
                </el-form-item>
              </template>
            </sys-common-search>
          </div>
        </search-btn-view>
      </div>
      <div class="returnToProvider-mgr-table-div">
        <el-table fit stripe border :data="returnMaterialToProviderData" highlight-current-row @selection-change="checkOrder"
          height="parent" style="width:100%;">
          <el-table-column sortable prop="id" label="采购单号" min-width="140px" header-align="center">
          </el-table-column>
          <el-table-column sortable prop="companyOrderId" label="订单编号" min-width="140px" header-align="center"></el-table-column>
          <el-table-column sortable prop="factoryNo" label="工厂型号" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable prop="coustomId" label="客户型号" min-width="120px" header-align="center"></el-table-column>

          <el-table-column sortable prop="providerName" label="供应商" min-width="100px" header-align="center"></el-table-column>
          <el-table-column sortable prop="materialName" label="物料名称" min-width="130px" header-align="center"></el-table-column>
          <el-table-column sortable prop="model" label="规格" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable prop="color" label="编号" min-width="100px" header-align="center"></el-table-column>
          <el-table-column sortable prop="colorDescription" label="描述" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable prop="materialDeptName" label="物料部门" min-width="120px" align="center"></el-table-column>

          <el-table-column sortable prop="count" label="退回数量" min-width="120px" align="center"></el-table-column>
          <el-table-column sortable prop="unit" label="退回单位" min-width="90px" align="center"></el-table-column>
          <el-table-column sortable prop="canInCount" label="可入库数" min-width="120px" align="center"></el-table-column>
          <el-table-column :resizable="false" label="入库单价" width="150px" header-align="center">
            <template slot-scope="scope">
              <el-input-number is-decimal-zero size="mini" :controls="false" :min="0" :precision="4" v-model="scope.row.unitPrice" style="width:140px;"
                @change="moneyChange(scope.row,'unitPrice')">
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="入库数量" width="150px" header-align="center">
            <template slot-scope="scope">
              <el-input-number is-decimal-zero size="mini" :controls="false" :min="0" :precision="4" v-model="scope.row.inCount" style="width:140px;">
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="入库结算数量" width="150px" header-align="center">
            <template slot-scope="scope">
              <el-input-number is-decimal-zero size="mini" :controls="false" :min="0" :max="scope.row.maxCount" :precision="4" v-model="scope.row.valuationCount"
                style="width:140px;" @change="moneyChange(scope.row,'valuationCount')">
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="入库金额" width="150px" header-align="center">
            <template slot-scope="scope">
              <el-input-number is-decimal-zero size="mini" :controls="false" :min="0" :precision="2" v-model="scope.row.totalMoney" style="width:140px;"
                @change="moneyChange(scope.row,'totalMoney')">
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="备注" width="150px" header-align="center">
            <template slot-scope="scope">
              <el-input size="mini" v-model="scope.row.remark" style="width:140px;">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" type="selection" width="50px" align="center" fixed="right">
          </el-table-column>
        </el-table>
      </div>
      <table-pagination v-if="pagination.totalCount!==0" :pagination="pagination" @change="pageChange"></table-pagination>
    </div>
  `;
  return {
    mixins: [
      tablePaginationMixin(),
      datePickerOptionsMixin('startDate', 'endDate')
    ],
    data: function () {
      var search = {
        materialName: '',
        model: '',
        color: '',
        colorDescription: '',
        providerName: '',
        materialDept: '',
        companyOrderId: '',
        orderId: '',
        factoryNo: '',
        customerNo: '',
        startDate: null,
        endDate: null
      };
      return {
        loading: false,
        moment: moment,
        selfApprovalPermission: false,
        returnMaterialToProviderData: [],
        checkData: [],
        searchField: ['materialName', 'model', 'color', 'providerName', 'materialDept', 'orderId', 'companyOrderId', 'factoryNo', 'customerNo'],
        search: _.cloneDeep(search),
        oldSearch: _.cloneDeep(search),
        pagination: {
          currentPage: 1,
          totalCount: 0,
          pageSize: 10
        }
      }
    },
    created: function () {
      this.checkApprovalPermission();
    },
    methods: {
      checkApprovalPermission: function (type) {
        var self = this;
        return PermissionUtil.ajaxCheckPermission(6).then(function (hasApproval) {
          self.selfApprovalPermission = hasApproval;
          return hasApproval;
        });
      },
      resetSearch: function () {
        this.search = _.cloneDeep(this.oldSearch);
      },
      searchData: function () {
        this.pagination.currentPage = 1;
        this.setMaterialDataList(true);
      },
      pageChange: function () {
        this.setMaterialDataList();
      },
      setMaterialDataList: function (isSearch) {
        if (!isSearch) {
          this.search = _.cloneDeep(this.oldSearch);
        }
        var search = this.search;
        var pagination = this.pagination;
        var currentPage = pagination.currentPage;
        var pageSize = pagination.pageSize;
        var start = (currentPage - 1) * pageSize;
        var postData = {
          start: start,
          length: pageSize,
          sourceType: 2
        }
        postData = this.setPostData(postData, search);
        this.loading = true;
        var self = this;
        ajaxRequest("returnWarehouseToProvider/getCanInCountByReturnToProviderData", postData, false).then(function (res) {
          if (isSearch) {
            self.oldSearch = _.cloneDeep(self.search);
          }
          var dataList = res.returnData;
          if (dataList.length === 0 && pagination.currentPage > 1) {
            self.pagination.totalCount = res.iTotalRecords;
            self.$nextTick(function () {
              self.setMaterialDataList(isSearch);
            });
            return;
          }

          for (var i = 0; i < dataList.length; i++) {
            var data = dataList[i];
            SysUtil.tableSetDeptData(data);

            var inCount = data.inCount;
            if (SysUtil.isEmpty(inCount)) {
              inCount = undefined;
            }
            data.inCount = inCount;

            var valuationCount = data.sumMoneyCount;
            var unitPrice = data.inCountPrice;
            var totalMoney = undefined;
            if (SysUtil.isEmpty(valuationCount)) {
              valuationCount = undefined;
              totalMoney = 0;
            } else {
              totalMoney = _.round(unitPrice * valuationCount, 2);
            }
            data.maxCount = valuationCount;
            data.valuationCount = valuationCount;

            data.unitPrice = unitPrice;
            data.totalMoney = totalMoney;
            data.remark = '';
          }
          self.returnMaterialToProviderData = dataList;
          self.pagination.totalCount = res.iTotalRecords;
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },
      //获取查询条件
      setPostData: function (postData, search) {
        var fields = ['orderId', 'companyOrderId', 'factoryNo', 'customerNo', 'materialName', 'model', 'color',
          'colorDescription', 'providerName'
        ];
        SysUtil.setPostData(postData, search, fields);

        var materialDept = search.materialDept;
        if (materialDept !== '') {
          postData.materialDeptId = materialDept.materialDeptId;
        }

        var startDate = search.startDate;
        if (startDate !== null) {
          postData.startDate = moment(startDate).format('YYYY-MM-DD');
        }

        var endDate = search.endDate;
        if (endDate !== null) {
          postData.endDate = moment(endDate).format('YYYY-MM-DD');
        }
        return postData;
      },
      checkOrder: function (selection) {
        this.checkData = selection;
      },
      saveData: function (isAduit) {
        var materialList = this.checkData;
        if (materialList.length === 0) {
          this.$alert('请选择物料', '信息');
          return;
        }

        var postData = [];
        for (var i = 0; i < materialList.length; i++) {
          var material = materialList[i];
          var code = this.checkValid(material);
          if (code !== '') {
            var msg = i18n.getMsg(`returnOrder.createOrderWarehouse.error.${code}`);
            this.$alert(msg, '信息');
            return;
          }

          var materialPostData = {
            id: material.id,
            count: material.inCount,
            sumMoneyCount: material.valuationCount,
            inCountPrice: material.unitPrice,
            inOutMoney: material.totalMoney,
            remark: material.remark
          };
          postData.push(materialPostData);
        }

        this.loading = true;
        var self = this;
        ajaxRequest("returnWarehouseToProvider/saveInCountByReturnToProviderData", {
          warehouseData: JSON.stringify(postData),
          isAduit: isAduit
        }).then(function (msg) {
          self.loading = false;
          self.$alert(msg, "信息", {
            callback: function () {
              self.setMaterialDataList();
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      checkValid: function (material) {
        var fields = ['unitPrice', 'inCount', 'valuationCount', 'totalMoney'];
        for (var i = 0; i < fields.length; i++) {
          var field = fields[i];
          var value = material[field];
          if (value === undefined) {
            return field;
          }

          if (['valuationCount', 'totalMoney'].indexOf(field) !== -1) {
            continue;
          }

          if (value === 0) {
            return field + 'IsZero';
          }
        }

        if (material.inCount > material.canInCount) {
          return 'inCount>canInCount';
        }
        return '';
      },

      deleteData: function () {
        var checkData = this.checkData;
        if (checkData.length === 0) {
          this.$alert('请选择需要删除的采购单物料', '信息');
          return;
        }

        var self = this;
        this.$confirm('确认删除所选择的采购单物料吗?', '删除确认').then(function () {
          self.toDeleteData(checkData);
        }).catch(function () {});
      },

      toDeleteData: function (orders) {
        var purchaseIds = _.map(orders, 'purchaseDetailId');
        var self = this;
        ajaxRequest('returnWarehouseToProvider/deleteReturnInFrom', {
          purchaseIdArray: JSON.stringify(purchaseIds)
        }).then(function () {
          self.$alert('成功批量删除采购单物料数据', '信息', {
            callback: function () {
              self.setMaterialDataList();
            }
          });
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      moneyChange: function (material, type) {
        var count = material.valuationCount;
        if (['unitPrice', 'valuationCount'].indexOf(type) !== -1) {
          var unitPrice = material.unitPrice;
          var totalMoney = SysUtil.calPrice(count, unitPrice, 'total', 2);
          material.totalMoney = totalMoney;
        } else {
          var totalMoney = material.totalMoney;
          var unitPrice = SysUtil.calPrice(count, totalMoney, 'unit', 4);
          material.unitPrice = unitPrice;
        }
      }
    },

    components: {
      SearchBtnView: SearchBtnView,
      SysCommonSearch: SysCommonSearch
    },

    template: template
  }
}();
